<template>
	<el-dialog title="新增新闻信息" :visible.sync="dialogVisible" width="85%">
		<el-form ref="form" :rules="rules" :model="form" label-width="100px" >
			<el-form-item label="新闻标题" prop="name">
				<el-input placeholder="" v-model="form.name"></el-input>
			</el-form-item>
      <el-form-item label="新闻作者" prop="writer">
        <el-input placeholder="" v-model="form.writer"></el-input>
      </el-form-item>
      <el-form-item label="新闻摘要" prop="outline">
        <el-input placeholder="" v-model="form.outline"></el-input>
      </el-form-item>

        <el-form-item label="新闻缩略图" prop="picture" class="imgCls">

            <el-upload class="avatar-uploader btnCls"
                       action="http://127.0.0.1:8089/admin/NewsCtl/newsPicture"
                       :show-file-list="false"
                       :on-success="handleAvatarSuccess"
            :headers="{adminToken:adminToken}">
              <div class="contentCls">

                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </div>
            </el-upload>
        </el-form-item>


      <el-form-item label="新闻类型" >
        <el-col :span="10">
          <el-checkbox-group v-model="form.newsTypeid">
            <el-checkbox v-for="newsType in newsTypeList" :label="newsType.id" :key="newsType.id">
              {{newsType.name}}
            </el-checkbox>
          </el-checkbox-group>
        </el-col>

      </el-form-item>
      <el-form-item label="是否在前台显示" prop="state" label-width="130px">
        <el-col :span="10">
          <el-radio v-model="form.state" :label="1">显示类型</el-radio>
          <el-radio v-model="form.state" :label="0">隐藏类型</el-radio></el-col>
      </el-form-item>

<!--文本编辑器-->
        <mavon-editor ref="md" v-model="form.content" :toolbars="toolbars"
                       style="background-color: #f0f9eb;" @imgAdd="imgAdd" @imgDel="imgDel"/>


			


		</el-form>
		<span slot="footer" class="dialog-footer">
			<el-button @click="dialogVisible = false">取 消</el-button>
			<el-button type="primary" @click="save('form')">保存</el-button>
		</span>
	</el-dialog>
</template>

<script>
	export default {
		name: "Add",
		data() {
			return {
        imageUrl: '',/*【不放在后端，只是为了在前端进行临时的显示缩略图】*/
				dialogVisible: false,
        newsTypeList: [],
        adminToken:'',
				form: {
          id:'',
          name: '',
          writer:'',
          picture:'',
          outline:'',
          state:'',
          newsTypeid:[],
          content:''
				},
				flag:true,
        rules: {
          name: [{
            required: true,
            message: '请输入新增的新闻类型！',
            trigger: 'blur'
          },
            {
              min: 1,
              max: 70,
              message: '长度在 1 到 50 个字符',
              trigger: 'blur'
            }
          ],
          writer: [{
            required: true,
            message: '请输入的新闻作者！',
            trigger: 'blur'
          },
            {
              min: 1,
              max: 50,
              message: '长度在 1 到 50 个字符',
              trigger: 'blur'
            }
          ],
          outline: [{
            required: true,
            message: '请输入的新闻摘要！',
            trigger: 'blur'
          },
            {
              min: 1,
              max: 200,
              message: '长度在 1 到 200 个字符',
              trigger: 'blur'
            }
          ],
          state: [{
            required: true,
            message: '请选择新闻类型是否在前台显示！',
            trigger: 'blur'
          }
          ]
				},
        toolbars:{
          bold: true, // 粗体
          italic: true, // 斜体
          header: true, // 标题
          underline: true, // 下划线
          strikethrough: true, // 中划线
          mark: true, // 标记
          quote: true, // 引用
          ol: true, // 有序列表
          ul: true, // 无序列表
          link: true, // 链接
          imagelink: true, // 图片链接
          code: true, // code
          table: true, // 表格
          fullscreen: true, // 全屏编辑
          readmodel: true, // 沉浸式阅读
          htmlcode: true, // 展示 html 源码
          help: true, // 帮助
          undo: true, // 上一步
          redo: true, // 下一步
          trash: true, // 清空
          save: false, // 保存（触发 events 中的 save 事件）
          navigation: true, // 导航目录
          subfield: true, // 单双栏模式
          preview: true // 预览
        },
			}
		},
		methods: {
      // 上传图片事件处理函数
      imgAdd (pos, file) {
        var formdata = new FormData();
        formdata.append('file', file);//前端封装图片数据 ‘file’向后端传递的 name
        this.$http({ //调用 java 后端上传图片到服务器端
          url: '/admin/NewsCtl/newsPicture',//自定义后端服务器地址,后端同文件上传功能
          data: formdata, method:"post", headers: { 'Content-Type': 'multipart/form-data'}, }).then((resp) => {//resp 后端响应数据
//将服务器返回的图片地址插入到编辑器内
          this.$refs.md.$img2Url(pos, "http://127.0.0.1:8088/"+resp.data.data);
        })
      },
      // 删除图片时间处理函数
      imgDel (pos) {
        var imgUrl=pos[0];//获取到图片服务器地址
        this.$http.get("/admin/newsCtl/deleteImg",{params:{imgurl:JSON.stringify(imgUrl)}})
            .then(function(res){
//删除回调
            })
      }
		  ,
      handleAvatarSuccess(res, file) {/*【这个对图片进行压缩处理，临时的缩略显示】*/
        this.imageUrl = URL.createObjectURL(file.raw);
        if(res.code==200){
          this.form.picture=res.data;
          this.$message({
            showClose: true,
            message: '恭喜你，上传成功✔',
            type: 'success'
          });
        }else if(res.code==401){
          this.$message({
            showClose: true,
            message: 'token验证失败',
            type: 'waring'
          });
        }else if(res.code==500){
          this.$message({
            showClose: true,
            message: '系统忙！',
            type: 'waring'
          });
        }

      },
			save(reffrom) {
        //数据向后端发送进行验证
        //$refs是一个引用
        this.$refs[reffrom].validate((valid) => {
          if (valid) {
            //如果发送成功，跳转到其他组件
            //【跳转语句】
            this.$http.post("admin/NewsCtl/saveNews", this.form).then((resp) => {
              if (resp.data.code == 200) {
                this.$message({
                  showClose: true,
                  message: '恭喜你，修改成功✔',
                  type: 'success'
                });
                this.$router.go();
              }
            })
          }
        });

			}
		},
		mounted() {
			this.$http.get("admin/NewsCtl/findNewsTypeList").then((res) => {
				if (res.data.code == 200) {
					this.newsTypeList = res.data.data;
				}
			})
      this.adminToken=sessionStorage.getItem("adminToken");
		}
	}
</script>

<style scoped>

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
}

div.imgCls div.avatar-uploader{
display: flex;
}

div.imgCls div.btnCls div.contentCls{
  border: 2px dashed rgb(83, 199, 176);
  width: 100px;
  height: 100px;
  background-color: bisque;
}

</style>